package org.dh2580.netty.demo.netty.protocol.privately;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import com.alibaba.fastjson.JSON;

/**
 * @Author: hao.deng
 * @Date: 2019/5/8-下午6:30
 */
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;

        if (message.getHeader() != null && message.getHeader().getType() == NettyMessageType.HEARTBEAT_REQ.getValue()) {
            System.out.println("Receive client heart beat message: -> " + JSON.toJSONString(msg));

            NettyMessage heatBeat = new NettyMessage();

            NettyHeader header = new NettyHeader();
            header.setType(NettyMessageType.HEARTBEAT_RESP.getValue());

            heatBeat.setHeader(header);

            ctx.writeAndFlush(heatBeat);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();

        ctx.close();

        ctx.fireExceptionCaught(cause);
    }
}
